import { View, Text, Image, ScrollView, } from '@tarojs/components';
import React, { Component } from 'react'
import Taro from '@tarojs/taro'
import { getRiskAssessment, submitRiskApproval } from '@/services/api/eligible_investors';
import { findMapsByFieldNameAndDictItemValue, queryRiskSection } from '@/services/api/common';
import { formatDate } from '@/utils/fomatter';
import { Toast, Button } from '@antmjs/vantui';
import { stringifyUrl } from 'query-string';


import './index.scss'




interface RiskAssessmentDetailProps {

}


class RiskAssessmentDetail extends Component<RiskAssessmentDetailProps, any> {
  constructor(props: RiskAssessmentDetailProps) {
    super(props);
  }

  state = {
    navBackGroundColor: 'rgba(255, 0, 0,0)',
    params: {},
    data: {},
    riskSection: [],
  }

  backColor = { '-1': '#77828F', '0': '#77828F', '1': '#009C71', '2': '#8020CC', '3': '#3A5FD4', '4': '#CE6F00', '5': '#A42828', }
  backTopColor = { '-1': '#E8EBEF', '0': '#E8EBEF', '1': '#80FFDC', '2': '#FDEAFF', '3': '#D8E2FF', '4': '#FFF2C5', '5': '#fff7dc', }
  textFColor = { '-1': '#DBDFE5', '0': '#DBDFE5', '1': '#B3EADB', '2': '#F1DEFF', '3': '#C4D3FF', '4': '#FFDDB6', '5': '#F5C6C6', }
  textPJColor = { '-1': '#ffffff', '0': '#ffffff', '1': '#02956C', '2': '#5C0A9C', '3': '#3056CC', '4': '#CC7209', '5': '#B23434', }
  textBackColor = { '-1': '#414D5E', '0': '#414D5E', '1': '#EDFAF7', '2': '#FAF3FF', '3': '#F1F5FF', '4': '#FFF7EE', '5': '#FDF2F2' }
  numBackColor = { '-1': '#414d5e3f', '0': '#414d5e3f', '1': '#015d433f', '2': '#5014803f', '3': '#1e35803f', '4': '#8048053f', '5': '#6f20203f', }

  // 建议在页面初始化时把 getCurrentInstance() 的结果保存下来供后面使用，
  // 而不是频繁地调用此 API
  $instance = Taro.getCurrentInstance()

  componentWillMount() {

    this.getRiskSection();
    // 获取传递的 map 对象
    var params = this.$instance.router?.params

    if (params != null) {
      this.setState({ params: params })
    }
    if (params != null && params['answers'] != null) {
      this.setState({ data: params, })
    } else {
      getRiskAssessment().then((resp) => {
        if (resp.code == 200) {
          if (params != null && params['isJG'] !== null) {
            resp.data['isJG'] = params['isJG']
          }
          this.setState({ data: resp.data })
        }
      })
    }

    const preloadData = this.$instance.preloadData
    if (preloadData != null && Object.keys(preloadData).length > 0) {
      this.setState({ params: preloadData })
    }
    this.setState({
      opacity: 0
    })
    Taro.preload({})  // 清空
  }


  // 获取分险名称
  getRiskSection() {
    queryRiskSection().then((resp) => {
      if (resp.code === 200) {
        this.setState({ riskSection: resp.data })
      }
    })
  }


  // 基金产品评级
  getRiskAssessmentItem() {
    const { data } = this.state;
    var riskAccept = data['riskAccept']
    const views: any = []
    for (let index = 1; index <= Number(riskAccept); index++) {
      console.log(index);
      views.push(<View className='risk-item' style={{ background: this.textBackColor[data['riskAccept']], color: this.textPJColor[data['riskAccept']] }}>{`R${index}`}</View>);
    }
    return views;
  }

  //
  getRiskAssessmentName() {
    const { riskSection, data } = this.state;
    var riskAssessmentName = ''
    for (let index = 0; index < riskSection.length; index++) {
      const element = riskSection[index];
      if (element['riskAccept'] == data['riskAccept']) {
        riskAssessmentName = element['riskAcceptName'];
      }
    }
    return riskAssessmentName
  }

  // 获取投资期限
  getTermofInvestment() {
    const { data } = this.state;
    var answers = data['answers']
    console.log(answers)
    var optContent = ''
    for (let index = 0; index < answers.length; index++) {
      const element = answers[index];
      if (element['returnType'] === 1 || element['returnType'] === "1") {
        optContent = element['optContent'];
      }
    }
    return optContent
  }

  // 获取投资品种
  getInvestmentVarieties() {
    const { data } = this.state;
    var answers = data['answers']
    var optContent = ''
    console.log(answers)
    for (let index = 0; index < answers.length; index++) {
      const element = answers[index];
      if (element['returnType'] === 2 || element['returnType'] === "2") {
        optContent = element['optContent'];
      }
    }
    return optContent
  }

  //
  getCpRiskFormUserRisk() {
    // R1 / R2 / R3
    const { data } = this.state;
    var riskAccept = data['riskAccept']
    var level = ''
    for (let index = 1; index <= Number(riskAccept); index++) {
      if (index == 1) {
        level = `R${index}`;
      } else {
        level = level + ' / ' + `R${index}`;
      }
    }
    return level;
  }

  //提交审核 -- 审核通过才会有这个按钮
  sumitRisk() {
    const { data } = this.state;
    submitRiskApproval(data['answerId']).then((resp) => {
      if (resp.code === 200) {
        Toast.show('已提交审核')
      }
    })
  }

  resetRisk() {
    var params = this.$instance.router?.params
    Taro.redirectTo({
      url: stringifyUrl({ url: '/eligible_investors/risk_assessment/index', query: params }, { encode: false })
    });
  }

  onbackList() {
    Taro.navigateBack();
  }

  onPageScroll(e) {
    if (e.detail.scrollTop < 50) {
      this.setState({
        navBackGroundColor: 'rgba(255, 0, 0,0)'
      })
    } else if (e.detail.scrollTop < 200) {
      // 计算滑动比例
      const ratio = Math.min(e.detail.scrollTop / 200, 1);
      const newBackgroundColor = `rgba(255, 255, 255, ${ratio})`;
      this.setState({
        navBackGroundColor: newBackgroundColor
      })
    } else {
      this.setState({
        navBackGroundColor: '#ffffff',
      })
    }
  }

  onScrollToUpper(e) {
    this.setState({
      navBackGroundColor: 'rgba(255, 0, 0,0)'
    })
  }

  render() {
    const { safeArea, statusBarHeight } = Taro.getSystemInfoSync();
    const { data, params, navBackGroundColor } = this.state;
    var maps = {}
    if (Object.keys(data).length > 0 && data.hasOwnProperty('riskAccept')) {
      maps = findMapsByFieldNameAndDictItemValue('risk_accept', data['riskAccept']);
      console.log(maps);

    }

    return (
      <>
        <View className='nav' style={{ paddingTop: statusBarHeight, height: statusBarHeight + 44, backgroundColor: navBackGroundColor }}>
          <View className='nav-back' onClick={() => this.onbackList()} >
            <Image src={require("@/assets/icons//public/nav_back_white.svg")} style='height:24px;width:24px;'></Image>
            {/* <IconFont name='nav_back_white' color='red' size={24}></IconFont> */}
          </View>
          <View className='nav_right' ></View>
        </View>

        {
          (Object.keys(data).length > 0 && data.hasOwnProperty('riskAccept'))
            ?
            <ScrollView className='page' style={{ background: this.backColor[data['riskAccept']] }} scrollY
              enhanced
              onScroll={(detail) => this.onPageScroll(detail)}
              onScrollToUpper={(detail) => this.onScrollToUpper(detail)}
            >
              <View
                className='content' style={{ paddingTop: statusBarHeight + 44 + 8, }}

              >
                <View className='content-top'>
                  <Text className='name'>评测结果</Text>
                  <View className='numerical' style={{ borderColor: this.numBackColor[data['riskAccept']] }}>
                    <View className='item'>
                      <Text className='num'>{data['quesInvestNum']}</Text>
                      <Text style={{ color: this.textFColor[data['riskAccept']] }}>测评分数</Text>
                    </View>
                    <View className='item'>
                      <Text className='num'>{maps['dictItemName']}</Text>
                      <Text style={{ color: this.textFColor[data['riskAccept']] }}>风险等级</Text>
                    </View>
                    <View className='dashed-ver-line view-center'></View>
                  </View>
                  <View className='sub sub-1'>{`您的风险承受能力类型为：${this.getRiskAssessmentName()}`}</View>
                  <View className='sub'>
                    <Text>适合您的基金产品评级为：</Text>
                    <View className='risk'>
                      {
                        this.getRiskAssessmentItem()
                      }
                    </View>
                  </View>
                  <View className='sub'>{`评测有效期至：${formatDate(data['assessmentExpires'], 'yyyy年MM月dd日')}`}</View>
                </View>
                <View className='content-desc'>
                  <View className='grid-container'>
                    <View className='grid-row'>
                      <View className='grid-item '>评测分数</View>
                      <View className='grid-item '>风险等级</View>
                      <View className='grid-item grid-item-2'>适应产品等级</View>
                    </View>
                    <View className='grid-row'>
                      <View className='grid-item '>0-24 分</View>
                      <View className='grid-item '>未通过</View>
                      <View className='grid-item grid-item-2'>-</View>
                    </View>
                    <View className='grid-row'>
                      <View className='grid-item '>25-48 分</View>
                      <View className='grid-item '>保守型</View>
                      <View className='grid-item grid-item-2'>R1</View>
                    </View>
                    <View className='grid-row'>
                      <View className='grid-item'>49-60 分</View>
                      <View className='grid-item'>谨慎型</View>
                      <View className='grid-item grid-item-2'>R1/R2</View>
                    </View>
                    <View className='grid-row'>
                      <View className='grid-item'>61-78 分</View>
                      <View className='grid-item'>稳健型</View>
                      <View className='grid-item grid-item-2'>R1/R2/R3</View>
                    </View>
                    <View className='grid-row'>
                      <View className='grid-item'>79-88 分</View>
                      <View className='grid-item'>积极型</View>
                      <View className='grid-item grid-item-2'>R1/R2/R3/R4</View>
                    </View>
                    <View className='grid-row'>
                      <View className='grid-item'>89-100 分</View>
                      <View className='grid-item'>激进型</View>
                      <View className='grid-item grid-item-2'>R1/R2/R3/R4/R5</View>
                    </View>
                  </View>
                  <Text className='title title-1'>尊敬的投资者：</Text>
                  <View className='dashed-hor-line line'></View>
                  <Text className='subtile'>根据您/贵机构填写的 《投资者风险承受能力问卷》</Text>
                  <Text>一、您/贵机构的拟投资期限为：<Text className='use-status'>{this.getTermofInvestment()}</Text>；</Text>
                  <Text>二、您/贵机构的拟投资品种为：<Text className='use-status'>{this.getInvestmentVarieties()}</Text>；</Text>
                  <Text>三、与您的风险承受能力等级可直接相匹配的产品或服务为：<Text className='use-status'>{this.getCpRiskFormUserRisk()}</Text>。</Text>
                  <Text className='title'>本公司在此郑重提醒：</Text>
                  <Text className='subtile'>本公司向您/贵机构销售的金融产品或提供的金融服务将以您的风险承受能力等级和投资品种、期限为基础。投资者风险承受能力评测结果仅供您/贵机构在做投资决策或公司向投资者提供产品或服务时参考，并不构成投资建议。</Text>
                  <View className='desc-sure'>本人/本机构经贵公司提示，已充分知晓贵公司向本人/本机构提供的产品或服务将以此次风险承受能力为基础。本人/本机构根据自身的风险承受能力，对自身的投资行为做出审慎判断。
                    本确认书系本人/本机构独立、自主、真实的意思表示，特此确认。</View>
                </View>
              </View>
              {/* {
                params.isOldRisk ?
                  <View className='bottom' style={{ paddingBottom: safeArea.top + 12 }}>
                    <Button className='left-button' onClick={this.resetRisk.bind(this)}>重新测评</Button>
                    {
                      (params && params['investConfirmAuthStatus'] === '2' && params['showSubmit'] === '1') ? <Button className='right-button' onClick={this.sumitRisk.bind(this)}>提交</Button> : null
                    }
                    {
                      (params && params['investConfirmAuthStatus'] !== '2') ? <Button className='right-button right-button-back' onClick={this.onbackList.bind(this)}>返回</Button> : null
                    }
                  </View>
                  :
                  <View className='bottom' style={{ paddingBottom: safeArea.top + 12 }}>
                    <Button className='finish-button right-button-back' onClick={this.onbackList.bind(this)}>完成</Button>
                  </View>
              } */}
              <View className='bottom' style={{ paddingBottom: safeArea.top + 12 }}>
                <Button className='finish-button right-button-back' onClick={this.onbackList.bind(this)}>完成</Button>
              </View>

            </ScrollView> : <View></View>

        }
        <Toast />
      </>
    );

  }
}

export default RiskAssessmentDetail;
